#include "RTPTransfer.h"
#include <rtppacket.h>

using namespace ipsound;

RTPTransfer::RTPTransfer( MutexBuffer* recieveBuf )
:recieveBuf ( recieveBuf )
,bufEvent( 0 )
,eventDataSize( 0 )
,recievedDataSize( 0 )
,eventSent( false )
{
}

void RTPTransfer::SetBufEvent( HANDLE bufEvent, const size_t& eventDataSize )
{
	this->bufEvent = bufEvent;
	this->eventDataSize = eventDataSize;
}

RTPTransfer::~RTPTransfer()
{
}

void RTPTransfer::OnPollThreadStep()
{
	BeginDataAccess();

	if (GotoFirstSourceWithData())
	{
		do
		{
			RTPPacket *pack;			
			while ((pack = GetNextPacket()) != NULL)
			{
				size_t written = recieveBuf->Write( pack->GetPayloadData(), pack->GetPayloadLength() );
				if(!eventSent)
				{
					recievedDataSize += written;
					if(recievedDataSize >= eventDataSize)
					{
						SetEvent(bufEvent);
						eventSent = true;
					}
				}
				DeletePacket(pack);
			}
		} while (GotoNextSourceWithData());
	}
		
	EndDataAccess();
}